//
//  MTEnvSwitchViewController.swift
//  MT
//
//  Created by zhang qiang on 2018/12/19.
//  Copyright © 2019年 张强. All rights reserved.
//

import UIKit
import SnapKit
import MTCategory

class MTEnvSwitchViewController: BaseViewController {
    
    
    let enviromentList: [String] = ["Developer", "Test", "Staging", "Relesae", "IM", "back"]
    
    lazy var tableView: UITableView = {
        let t = UITableView(frame: .zero, style: .plain)
        t.register(UITableViewCell.self, forCellReuseIdentifier: "enviromentCell")
        t.delegate = self
        t.dataSource = self
        return t
    }()

    private var complete: ((String) -> ())?
    
    public init(_ complete: ((String) -> ())? = nil) {
        self.complete = complete
        super.init()
    }
    
    required public init(rounterParams params: Dictionary<String, Any>?) {
        fatalError("init(rounterParams:) has not been implemented")
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(closeNone))
        
        self.view.backgroundColor = .white
        
        view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(100)
            make.bottom.equalToSuperview().offset(-ScreenBottomExtraOffset)
        }
        
    }
    
    @objc private func closeNone() {
        self.dismiss(animated: true, completion: nil)
        self.navigationController?.popToRootViewController(animated: true)
    }
    
    @objc private func close(_ complete: (() -> Void)? = nil) {
        /// 关闭当前控制器
        self.dismiss(animated: true, completion: complete)
        self.navigationController?.popToRootViewController(animated: true)
    }
}



extension MTEnvSwitchViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.enviromentList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "enviromentCell", for: indexPath)
        
        cell.textLabel?.text = self.enviromentList[indexPath.row]
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let index = indexPath.row + 1
        
        if index == 5 {
            UIApplication.mt_keyWindow?.rootViewController = nil
            UIApplication.mt_keyWindow?.rootViewController = JCMainTabBarController()
            return;
        }
        
        if index == 6  {
            UIApplication.mt_keyWindow?.rootViewController = nil
            UIApplication.mt_keyWindow?.rootViewController = BaseTabBarViewController()
            return
        }
        
        let envString: String = self.enviromentList[indexPath.row]
        let currentEnv: Int = UserDefaults.Enviroment.env.storedInt
        
        /// 清除用户信息 - 要求重新登录 token 机制决定
        // MTAccountManager.share().logout()
        
        /// 如果是当前环境不切换
        if currentEnv == index {
            // MTNotice.share().show(image: .info, text: "已经是当前环境无需切换", y: MTNoticeY)
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) {
                self.close()
            }
            return 
        }
        
        /// 设置环境参数
        UserDefaults.Enviroment.env.store(value: index)
        
        self.complete?(envString)
        
        self.close {
            UserDefaults.Enviroment.envSwitchBtnDidMoveToWindow.store(value: false)
            let login: MTLoginViewController = MTLoginViewController()
            let nav: BaseNavController = BaseNavController(rootViewController: login)
            nav.modalPresentationStyle = .overFullScreen
            UIApplication.mt_keyWindow?.rootViewController?.present(nav, animated: true, completion: nil)
        }
    }
}
